﻿
namespace Patterns4Net.Tests.Core.CecilExtensions
{
    using System.Linq;
    using Mono.Cecil.Cil;
    using NUnit.Framework;
    using Patterns4Net.Core.CecilExtensions;

    [TestFixture]
    public class StackObserverTest
    {
        [Test]
        public void Discover_Call_Of_Member_Function()
        {
            var method = typeof(StackObserverTest).GetTypeDefinition().Methods.First(x => x.Name == "CallMyFunc");
            var result = StackObserver.CreateStackStates(method);

            var instructions = method.Body.Instructions;
            int callIndex = instructions.IndexOf(instructions.First(x => x.OpCode == OpCodes.Call));

            var stack = result[callIndex - 1]; // we want to know how the stack looked like before call to method
            Assert.IsTrue(stack.Last().IsThisParameter);
        }

        private int CallMyFunc(int x)
        {
            int someCode = x * 4;
            this.MyFunc(); // this call interrests us, we want to know whether it is done on 'this' instance
            int y = someCode + 2;
            return y + x;
        }

        private void MyFunc()
        {            
        }
    }
}
